package com.bootdo.app.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.system.domain.Template;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class WeChatConfig {

	public static String getAccessToken(String APPID,String appsecret_key) throws IOException {
		// 访问微信服务器
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret="
				+ appsecret_key;
		URL getUrl = new URL(url);
		HttpURLConnection http = (HttpURLConnection) getUrl.openConnection();
		http.setRequestMethod("GET");
		http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		http.setDoOutput(true);
		http.setDoInput(true);
		http.connect();
		InputStream is = http.getInputStream();
		int size = is.available();
		byte[] b = new byte[size];
		is.read(b);
		String message = new String(b, "UTF-8");
		JSONObject json = JSON.parseObject(message);
		System.out.println(json.toString());
		String accesstoken = json.getString("access_token");
		//Integer expires_in = new Integer(json.getString("expires_in"));
		return accesstoken;
	}

    public  String weChatGetOpenId(String code) throws Exception {
        //向微信后台发起请求获取openid的url
        String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        String requestUrl = WX_URL.replace("APPID", "wxdbeb0f99a6916fca").replace("SECRET", "da494996981b1fa9df048e0f3a0cfaa8").replace("JSCODE", code).replace("authorization_code", "authorization_code");
        System.out.println("请求链接为 ---" + requestUrl);
        HttpRequestor httpRequestor = new HttpRequestor();
        String weChatUtil = httpRequestor.doGet(requestUrl);
        JSONObject jsonObject = JSON.parseObject(weChatUtil);
        //获取用户的openId
        String openid = jsonObject.getString("openid");
        System.out.println(jsonObject);
        return openid;
    }

    public  Map weChatGetOpenIdPro(String code) throws Exception {
        Map map = new HashMap();
        //向微信后台发起请求获取openid的url
        String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        String requestUrl = WX_URL.replace("APPID", "wxdbeb0f99a6916fca").replace("SECRET", "da494996981b1fa9df048e0f3a0cfaa8").replace("JSCODE", code).replace("authorization_code", "authorization_code");
        System.out.println("请求链接为 ---" + requestUrl);
        HttpRequestor httpRequestor = new HttpRequestor();
        String weChatUtil = httpRequestor.doGet(requestUrl);
        JSONObject jsonObject = JSON.parseObject(weChatUtil);
        //获取用户的openId
        String openid = jsonObject.getString("openid");
        map.put("openid",openid);
        //获取用户unionid(如果用户没关注公众号,则获取不到)
        if (jsonObject.getString("unionid")!=null){
            map.put("unionid",jsonObject.getString("unionid"));
        }
        System.out.println(jsonObject);
        return map;
    }


    public static boolean sendTemplateMsg(Template template,String token) throws IOException {
       // String token = WeChatConfig.getAccessToken("wxdbeb0f99a6916fca", "da494996981b1fa9df048e0f3a0cfaa8");
        boolean flag = false;
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", token);
        String jsonString = template.toJSON();
        JSONObject jsonResult = CommonUtil.httpsRequest(requestUrl, "POST", jsonString);
        if (jsonResult != null) {
            int errorCode = jsonResult.getInteger("errcode");
            String errorMessage = jsonResult.getString("errmsg");
            if (errorCode == 0) {
                flag = true;
            } else {
                System.out.println("模板消息发送失败:" + errorCode + "," + errorMessage);
                flag = false;
            }
        }
        return flag;
    }


    public static Boolean sendTemplateMessageMax(String openId,String formId,String templateId,String keyword1,String keyword2,String keyword3,String keyword4,String keyword5,String keyword6,String token) throws IOException {
        Template tem = new Template();
        // tem.setTemplateId("qBZ3BAC-Qs_LrcOqQ-NtVz7MM7bUKZ8ZubweSM0Wphg");
        tem.setTemplateId(templateId);
        tem.setFormId(formId);
        tem.setTopColor("#00DD00");
        // tem.setToUser("oA5fM4rLOTbXX30h_0OzvO0chho4");
        tem.setToUser(openId);
        tem.setUrl("");
        List<TemplateParam> paras = new ArrayList<TemplateParam>();
        if (keyword1 != null) {
            paras.add(new TemplateParam("keyword1", keyword1, "#0044BB"));
        }
        if (keyword2 != null) {
            paras.add(new TemplateParam("keyword2", keyword2, "#0044BB"));
        }

        if (keyword3 != null) {
            paras.add(new TemplateParam("keyword3", keyword3, "#0044BB"));
        }
        if (keyword4 != null) {
            paras.add(new TemplateParam("keyword4", keyword4, "#0044BB"));
        }
        if (keyword5 != null) {
            paras.add(new TemplateParam("keyword5", keyword5, "#0044BB"));
        }
        if (keyword6 != null) {
            paras.add(new TemplateParam("keyword6", keyword6, "#0044BB"));
        }
//测试数据
//        paras.add(new TemplateParam("keyword1", "坤铭", "#0044BB"));
//        paras.add(new TemplateParam("keyword2", "2018-08-25", "#0044BB"));
//        paras.add(new TemplateParam("keyword3", "大李子", "#AAAAAA"));
        tem.setTemplateParamList(paras);
        boolean result = WeChatConfig.sendTemplateMsg(tem,token);
        return result;

    }



    public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();

        // 从request中取得输入流
        InputStream inputStream = request.getInputStream();
        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();
        // 遍历所有子节点
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }
        // 释放资源
        inputStream.close();
        inputStream = null;

        return map;
    }



}
